package model

import (
	"encoding/json"
	"fmt"
	"gowork/preferentialActivities/utils"
	"time"
)

type PreferentialActivities struct {
	Id int64 `xorm:"pk autoincr"`
	ActivityType int   //  1买A送B   2满额送
	WeightValue int
	ParticipateType int   //  1按单次   2按人次
	CanParticipateCount int
	FullAmount int64
	State int
	ActivityStartTime time.Time
	ActivityEndTime time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
	PurchasePackage *PurchasePackage `xorm:"-"`
	ComplimentaryPackageList []*ComplimentaryPackage `xorm:"-"`
}

type PurchasePackage struct {
	Id int64 `xorm:"pk autoincr"`
	PreferentialActivitieId int64
	PackageName string
	PackageListStr string `xorm:"varchar(20480)"`
	PackageList []*Package `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ComplimentaryPackage struct {
	Id int64 `xorm:"pk autoincr"`
	PreferentialActivitieId int64
	PackageName string
	PackageListStr string `xorm:"varchar(20480)"`
	PackageList []*Package `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Package struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	Number int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type PutOrder struct {
	OrderType int
	CustomerId int64
	CustomerName string
	NextSinglePersonId int64
	NextSinglePersonName string
	Meal string
	MealList []*Package
	TotalPrice int64
	Region string
}

type ParticipationRecord struct {
	Id int64 `xorm:"pk autoincr"`
	PreferentialActivitieId int64
	CustomerId int64
	CustomerName string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (pa *PreferentialActivities)InsertPreferentialActivities(pav *PreferentialActivities)(map[string]interface{}, error){

	w := new(utils.Worker)

	pav.Id = w.GetId()
	pav.CreatedAt = time.Now()
	pav.UpdatedAt = time.Now()
	x.Insert(pav)

	if pav.ActivityType == 1 {
		data, err := json.Marshal(pav.PurchasePackage.PackageList)
		if err != nil {
			return map[string]interface{}{"message": "序列化失败", "code": "500"}, err
		}
		pav.PurchasePackage.Id = w.GetId()
		pav.PurchasePackage.PreferentialActivitieId = pav.Id
		pav.PurchasePackage.PackageListStr = string(data)
		pav.PurchasePackage.CreatedAt = time.Now()
		pav.PurchasePackage.UpdatedAt = time.Now()
		x.Insert(pav.PurchasePackage)
	}

	for _, cpv := range pav.ComplimentaryPackageList{
		data, err := json.Marshal(cpv.PackageList)
		if err != nil {
			return map[string]interface{}{"message": "序列化失败","code":"500"}, err
		}
		cpv.Id = w.GetId()
		cpv.PackageListStr = string(data)
		cpv.PreferentialActivitieId = pav.Id
		cpv.CreatedAt = time.Now()
		cpv.UpdatedAt = time.Now()
		x.Insert(cpv)
	}

	return map[string]interface{}{"message": "成功","code":"200"}, nil
}

func (pa *PreferentialActivities)InsertOrder(o *PutOrder)(map[string]interface{}, error){

	w := new(utils.Worker)

	var pList []*Package

	var paList []*PreferentialActivities
	x.SQL("select * from preferential_activities where activity_start_time <= ? and activity_end_time >= ? and state = ?", time.Now().Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05"), 1).Find(&paList)
	//x.Where("sctivity_start_time <= ?", time.Now().Format("2006-01-02 15:04:05")).
	//	And("activity_end_time >= ?", time.Now().Format("2006-01-02 15:04:05")).
	//	And("state = ?", 1).Find(&paList)
	fmt.Println(paList)

	for _, pa := range paList{

		x.Where("preferential_activitie_id = ?", pa.Id).Find(&pa.ComplimentaryPackageList)

		if pa.ActivityType == 2{
			if o.TotalPrice >= pa.FullAmount{
				if pa.ParticipateType == 2{
					count, err := x.Where("preferential_activitie_id = ?", pa.Id).And("customer_id = ?", o.CustomerId).Count(new(ParticipationRecord))
					if err != nil{
						return map[string]interface{}{"message": "查询失败","code":"400"}, err
					}

					if count >= int64(pa.CanParticipateCount){
						return map[string]interface{}{"message": "该满额送活动，该客户的参与次数已达到上限","code":"400"}, err
					}

					for _, cp := range pa.ComplimentaryPackageList{
						if err := json.Unmarshal([]byte(cp.PackageListStr), &cp.PackageList); err == nil {
							for _, p :=range cp.PackageList{
								pList = append(pList, p)
							}
						}else {
							return map[string]interface{}{"message": "反序列化失败","code":"400"}, err
						}
					}
				}else if pa.ParticipateType == 1{
					var value int
					var tem int = int(o.TotalPrice / pa.FullAmount)
					fmt.Println("tem：", tem)
					if tem < pa.CanParticipateCount{
						value = tem
					}else {
						value = pa.CanParticipateCount
					}

					for i:=1; i<=value; i++ {
						fmt.Println("i：", i)
						for _, cp := range pa.ComplimentaryPackageList{
							if err := json.Unmarshal([]byte(cp.PackageListStr), &cp.PackageList); err == nil {
								for _, p :=range cp.PackageList{
									pList = append(pList, p)
								}
							}else {
								return map[string]interface{}{"message": "反序列化失败","code":"400"}, err
							}
						}
					}
				}
			}
		}else if pa.ActivityType == 1{
			var ppp PurchasePackage
			x.Where("preferential_activitie_id = ?", pa.Id).Get(&ppp)
			pa.PurchasePackage = &ppp
			fmt.Println("pa.PurchasePackage：", pa.PurchasePackage)
			if err := json.Unmarshal([]byte(pa.PurchasePackage.PackageListStr), &pa.PurchasePackage.PackageList); err == nil {
				var count int
				for _, pp := range pa.PurchasePackage.PackageList{
					for _, m := range o.MealList{
						if pp.Id == m.Id{
							if pa.ParticipateType == 1{
								count += 1
								if count <= pa.CanParticipateCount {
									fmt.Println("count：", count)
									for _, cp := range pa.ComplimentaryPackageList {
										if err := json.Unmarshal([]byte(cp.PackageListStr), &cp.PackageList); err == nil {
											for _, p := range cp.PackageList {
												pList = append(pList, p)
											}
										} else {
											return map[string]interface{}{"message": "反序列化失败", "code": "400"}, err
										}
									}
								}
							}else if pa.ParticipateType == 2{
								count, err := x.Where("preferential_activitie_id = ?", pa.Id).And("customer_id = ?", o.CustomerId).Count(new(ParticipationRecord))
								if err != nil{
									return map[string]interface{}{"message": "查询失败","code":"400"}, err
								}

								if count >= int64(pa.CanParticipateCount){
									return map[string]interface{}{"message": "该买A送B活动，该客户参与次数已达到上限","code":"400"}, err
								}

								for _, cp := range pa.ComplimentaryPackageList {
									if err := json.Unmarshal([]byte(cp.PackageListStr), &cp.PackageList); err == nil {
										for _, p := range cp.PackageList {
											pList = append(pList, p)
										}
									} else {
										return map[string]interface{}{"message": "反序列化失败", "code": "400"}, err
									}
								}
							}
						}
					}
				}

			}else {
				return map[string]interface{}{"message": "反序列化失败","code":"400"}, err
			}
		}

		var pr = ParticipationRecord{
			Id:           w.GetId(),
			PreferentialActivitieId: pa.Id,
			CustomerId:   o.CustomerId,
			CustomerName: o.CustomerName,
			CreatedAt:    time.Now(),
			UpdatedAt:    time.Now(),
		}
		x.Insert(&pr)
	}

	return map[string]interface{}{"message": "成功","code":"200", "data":pList}, nil
}
